import { useState } from 'react';
import type { ChatSession } from '../types/chat';
import './ChatHistory.css';

interface ChatHistoryProps {
  sessions: ChatSession[];
  currentSessionId: string | null;
  onSelectSession: (sessionId: string) => void;
  onNewChat: () => void;
  onDeleteSession: (sessionId: string) => void;
}

export function ChatHistory({
  sessions,
  currentSessionId,
  onSelectSession,
  onNewChat,
  onDeleteSession,
}: ChatHistoryProps) {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <>
      <button
        className="chat-history-toggle"
        onClick={() => setIsOpen(!isOpen)}
        aria-label="聊天记录"
      >
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <line x1="3" y1="12" x2="21" y2="12"></line>
          <line x1="3" y1="6" x2="21" y2="6"></line>
          <line x1="3" y1="18" x2="21" y2="18"></line>
        </svg>
      </button>
      {isOpen && (
        <>
          <div className="chat-history-overlay" onClick={() => setIsOpen(false)} />
          <div className="chat-history-sidebar">
            <div className="chat-history-header">
              <h2>聊天记录</h2>
              <button className="chat-history-close" onClick={() => setIsOpen(false)}>
                ✕
              </button>
            </div>
            <button className="chat-history-new" onClick={onNewChat}>
              + 新对话
            </button>
            <div className="chat-history-list">
              {sessions.length === 0 ? (
                <div className="chat-history-empty">暂无聊天记录</div>
              ) : (
                sessions.map((session) => (
                  <div
                    key={session.id}
                    className={`chat-history-item ${
                      currentSessionId === session.id ? 'active' : ''
                    }`}
                    onClick={() => {
                      onSelectSession(session.id);
                      setIsOpen(false);
                    }}
                  >
                    <div className="chat-history-item-title">{session.title}</div>
                    <div className="chat-history-item-meta">
                      <span>{session.messages.length} 条消息</span>
                      <span>·</span>
                      <span>{session.model}</span>
                    </div>
                    <button
                      className="chat-history-item-delete"
                      onClick={(e) => {
                        e.stopPropagation();
                        onDeleteSession(session.id);
                      }}
                      aria-label="删除"
                    >
                      ✕
                    </button>
                  </div>
                ))
              )}
            </div>
          </div>
        </>
      )}
    </>
  );
}

